///
/// 加载动画组件，支持多种动画类型和自定义样式

import 'package:flutter/material.dart';

import '../../core/elegance_theme.dart';

/// 加载图标模式枚举
enum ELoadingIconMode {
  /// 圆形模式
  circle,

  /// 半圆模式
  semicircle,

  /// 花朵模式
  flower,
}

/// 加载图标组件
class ELoadingIcon extends StatelessWidget {
  /// 创建ELoadingIcon组件
  const ELoadingIcon({
    super.key,
    this.show = true,
    this.color,
    this.textColor,
    this.vertical = false,
    this.mode = ELoadingIconMode.circle,
    this.size = 24,
    this.textSize = 15,
    this.text = '',
    this.timingFunction = Curves.easeInOut,
    this.duration = 1200,
    this.inactiveColor = Colors.transparent,
  });

  /// 是否显示动画
  final bool show;

  /// 图标颜色
  final Color? color;

  /// 提示文本颜色
  final Color? textColor;

  /// 图标和文字是否垂直排列
  final bool vertical;

  /// 模式选择
  final ELoadingIconMode mode;

  /// 加载图标的大小，单位px
  final double size;

  /// 加载文字的大小，单位px
  final double textSize;

  /// 文字内容
  final String text;

  /// 动画曲线
  final Curve timingFunction;

  /// 动画执行周期时间，单位ms
  final int duration;

  /// 图标的暗边颜色，仅mode为circle模式有效
  final Color inactiveColor;

  @override
  Widget build(BuildContext context) {
    // 如果不显示，返回空widget
    if (!show) {
      return const SizedBox.shrink();
    }

    // 获取主题和颜色
    final theme = context.eleganceTheme;
    final iconColor = color ?? theme.primaryColor;
    final textClr = textColor ?? theme.textSecondaryColor;

    // 根据模式创建加载动画
    Widget loadingAnimation;
    switch (mode) {
      case ELoadingIconMode.circle:
        loadingAnimation = _buildCircleLoading(iconColor, inactiveColor);
        break;
      case ELoadingIconMode.semicircle:
        loadingAnimation = _buildSemicircleLoading(iconColor);
        break;
      case ELoadingIconMode.flower:
        loadingAnimation = _buildFlowerLoading(iconColor);
        break;
    }

    // 构建整个组件
    Widget content;
    if (text.isEmpty) {
      // 只有图标
      content = loadingAnimation;
    } else {
      // 图标和文字组合
      content = vertical
          ? Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                loadingAnimation,
                const SizedBox(height: 8),
                _buildText(text, textClr),
              ],
            )
          : Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                loadingAnimation,
                const SizedBox(width: 8),
                _buildText(text, textClr),
              ],
            );
    }

    return content;
  }

  /// 构建圆形加载动画
  Widget _buildCircleLoading(Color color, Color inactiveColor) {
    return SizedBox(
      width: size,
      height: size,
      child: Stack(
        children: [
          // 背景圆（如果需要）
          if (inactiveColor != Colors.transparent)
            SizedBox(
              width: size,
              height: size,
              child: CircularProgressIndicator(
                strokeWidth: 2.0,
                valueColor: AlwaysStoppedAnimation<Color>(inactiveColor),
                backgroundColor: Colors.transparent,
              ),
            ),
          // 动画圆
          SizedBox(
            width: size,
            height: size,
            child: CircularProgressIndicator(
              strokeWidth: 2.0,
              valueColor: AlwaysStoppedAnimation<Color>(color),
              backgroundColor: Colors.transparent,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建半圆加载动画
  Widget _buildSemicircleLoading(Color color) {
    return SizedBox(
      width: size,
      height: size,
      child: _CustomSemicircleLoading(
        color: color,
        size: size,
        duration: duration,
        timingFunction: timingFunction,
      ),
    );
  }

  /// 构建花朵加载动画
  Widget _buildFlowerLoading(Color color) {
    return SizedBox(
      width: size,
      height: size,
      child: _CustomFlowerLoading(
        color: color,
        size: size,
        duration: duration,
        timingFunction: timingFunction,
      ),
    );
  }

  /// 构建文字组件
  Widget _buildText(String text, Color color) {
    return Text(
      text,
      style: TextStyle(color: color, fontSize: textSize),
    );
  }
}

/// 自定义半圆加载动画
class _CustomSemicircleLoading extends StatefulWidget {
  const _CustomSemicircleLoading({
    required this.color,
    required this.size,
    required this.duration,
    required this.timingFunction,
  });

  final Color color;
  final double size;
  final int duration;
  final Curve timingFunction;

  @override
  __CustomSemicircleLoadingState createState() =>
      __CustomSemicircleLoadingState();
}

class __CustomSemicircleLoadingState extends State<_CustomSemicircleLoading>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _animation;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      duration: Duration(milliseconds: widget.duration),
      vsync: this,
    )..repeat();
    _animation = CurvedAnimation(
      parent: _controller,
      curve: widget.timingFunction,
    );
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: _animation,
      builder: (context, child) {
        return Transform.rotate(
          angle: _animation.value * 2 * 3.141592653589793,
          child: CustomPaint(
            size: Size(widget.size, widget.size),
            painter: _SemicirclePainter(color: widget.color),
          ),
        );
      },
    );
  }
}

/// 半圆绘制器
class _SemicirclePainter extends CustomPainter {
  const _SemicirclePainter({required this.color});

  final Color color;

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = color
      ..strokeWidth = 2.0
      ..style = PaintingStyle.stroke
      ..strokeCap = StrokeCap.round;

    final center = Offset(size.width / 2, size.height / 2);
    final radius = (size.width - 2) / 2; // 减去描边宽度的一半

    // 绘制半圆
    canvas.drawArc(
      Rect.fromCircle(center: center, radius: radius),
      -3.141592653589793 / 2, // 从顶部开始
      3.141592653589793, // 半圆的角度
      false,
      paint,
    );
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return false;
  }
}

/// 自定义花朵加载动画
class _CustomFlowerLoading extends StatefulWidget {
  const _CustomFlowerLoading({
    required this.color,
    required this.size,
    required this.duration,
    required this.timingFunction,
  });

  final Color color;
  final double size;
  final int duration;
  final Curve timingFunction;

  @override
  __CustomFlowerLoadingState createState() => __CustomFlowerLoadingState();
}

class __CustomFlowerLoadingState extends State<_CustomFlowerLoading>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _animation;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      duration: Duration(milliseconds: widget.duration),
      vsync: this,
    )..repeat();
    _animation = CurvedAnimation(
      parent: _controller,
      curve: widget.timingFunction,
    );
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: _animation,
      builder: (context, child) {
        return Transform.rotate(
          angle: _animation.value * 2 * 3.141592653589793,
          child: CustomPaint(
            size: Size(widget.size, widget.size),
            painter: _FlowerPainter(
              color: widget.color,
              progress: _animation.value,
            ),
          ),
        );
      },
    );
  }
}

/// 花朵绘制器
class _FlowerPainter extends CustomPainter {
  const _FlowerPainter({required this.color, required this.progress});

  final Color color;
  final double progress;

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = color
      ..strokeWidth = 2.0
      ..style = PaintingStyle.stroke
      ..strokeCap = StrokeCap.round;

    final center = Offset(size.width / 2, size.height / 2);
    final radius = (size.width - 8) / 2; // 减去一些边距

    // 绘制多个圆弧，模拟花朵效果
    const int segments = 4;
    for (int i = 0; i < segments; i++) {
      final startAngle =
          (i * 2 * 3.141592653589793 / segments) +
          (progress * 2 * 3.141592653589793);
      const sweepAngle = 3.141592653589793 / 4; // 45度

      // 透明度随进度变化
      final alpha = (255 * (0.3 + 0.7 * ((progress + i / segments) % 1)))
          .toInt();
      paint.color = color.withAlpha(alpha);

      canvas.drawArc(
        Rect.fromCircle(center: center, radius: radius),
        startAngle,
        sweepAngle,
        false,
        paint,
      );
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return true;
  }
}
